package net.minhdiep.compassview;

import android.app.*;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.*;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import net.minhdiep.compassview.base.Item;
import net.minhdiep.compassview.components.MyAlarmReceiver;
import net.minhdiep.compassview.components.MyAlertFragment;
import net.minhdiep.compassview.components.MyViewFragment;
import net.minhdiep.compassview.components.NotificationReceiver;
import net.minhdiep.compassview.util.DownloadData;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.List;


/*
 * User: Minh Diep
 * Date: 6/8/13
 * Time: 12:10 AM
 */

public class MainActivity extends FragmentActivity implements DownloadData.OnListener {

    public static final String DEBUG = "net.minhdiep.tutorial";


    // Called at the start of the full lifetime.
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Initialize Activity and inflate the UI.


    }

    public void startFragAlert(View view){
        FragmentManager fragmentManager = getSupportFragmentManager();
        Fragment old_diff_id1 = fragmentManager.findFragmentById(R.id.view_container);
        Fragment old_diff_id2 = fragmentManager.findFragmentById(R.id.alert_container);
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        if (old_diff_id1 != null)
            fragmentTransaction.detach(old_diff_id1);
        if (old_diff_id2 != null)
            fragmentTransaction.detach(old_diff_id2);
        fragmentTransaction.add(R.id.alert_container, new MyAlertFragment());
        fragmentTransaction.commit();
    }

    public void startFragView(View view){
        FragmentManager fragmentManager = getSupportFragmentManager();
        Fragment old_diff_id1 = fragmentManager.findFragmentById(R.id.view_container);
        Fragment old_diff_id2 = fragmentManager.findFragmentById(R.id.alert_container);
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        if (old_diff_id1 != null)
            fragmentTransaction.detach(old_diff_id1);
        if (old_diff_id2 != null)
            fragmentTransaction.detach(old_diff_id2);
        fragmentTransaction.add(R.id.view_container, new MyViewFragment());
        fragmentTransaction.commit();
    }

    public void startAlert(View view) {
        EditText text = (EditText) findViewById(R.id.time);
        int i = Integer.parseInt(text.getText().toString());
        Intent intent = new Intent(this, MyAlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
                + (i * 1000), pendingIntent);
        Toast.makeText(this, "Alarm set in " + i + " seconds",
                Toast.LENGTH_LONG).show();
    }

    public void startNotif(View view){
        Intent intent = new Intent(this, NotificationReceiver.class);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

        // Build notification
        // Actions are just fake
        Notification notification = new Notification.Builder(this)
                .setContentTitle("New mail from " + "test@gmail.com")
                .setContentText("Subject").setSmallIcon(R.drawable.ic_launcher)
                .setContentIntent(pIntent)
                .addAction(R.drawable.ic_launcher, "Call", pIntent)
                .addAction(R.drawable.ic_launcher, "More", pIntent)
                .addAction(R.drawable.ic_launcher, "And more", pIntent).build();
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // Hide the notification after its selected
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        // ----------------------
        //      Add Sound
        //----------------------
        //a. Default sound
        notification.defaults |= Notification.DEFAULT_SOUND;

        //b. Custom sound from SD card
        notification.sound = Uri.parse("file:///sdcard/Ringtones/btdt.mp3");


        //----------------------
        //   Add Vibration
        //----------------------
        //a. Default vibration
        notification.defaults |= Notification.DEFAULT_VIBRATE;

        //b. Custom vibration
        long[] vibrate = {0,100,200,300};
        notification.vibrate = vibrate;


        //------------------------
        // Add Flashing Lights
        //------------------------
        //a. Default lights
        notification.defaults |= Notification.DEFAULT_LIGHTS;

        //b. Custom lights
        notification.ledARGB = 0xff00ff00;
        notification.ledOnMS = 300;
        notification.ledOffMS = 1000;
        notification.flags |= Notification.FLAG_SHOW_LIGHTS;

        notificationManager.notify(0, notification);
    }

    public void startXmlParser(View View) throws IOException, XmlPullParserException {
        String myUrl = "http://www.astrology.com/horoscopes/details/2013-03-31/aries-daily-extended?dst=rss%7Cast_horo%7Cdx&amp;play_horoscope=1#video-horoscope";
        ConnectivityManager connMgr = (ConnectivityManager)
                this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            new DownloadData(this).execute(myUrl);
        }
    }

    public void startCompassView(View view){
        Intent intent = new Intent(this, CompassViewActivity.class);
        startActivity(intent);
    }

    // Called after onCreate has finished, use to restore UI state
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        // Restore UI state from the savedInstanceState.
        // This bundle has also been passed to onCreate.
        // Will only be called if the Activity has been
        // killed by the system since it was last visible.
    }

    // Called before subsequent visible lifetimes
    // for an Activity process.
    @Override
    public void onRestart() {
        super.onRestart();
        // Load changes knowing that the Activity has already
        // been visible within this process.
    }

    // Called at the start of the visible lifetime.
    @Override
    public void onStart(){
        super.onStart();
        // Apply any required UI change now that the Activity is visible.
    }

    // Called at the start of the active lifetime.
    @Override
    public void onResume(){
        super.onResume();
        // Resume any paused UI updates, threads, or processes required
        // by the Activity but suspended when it was inactive.

    }

    // Called to save UI state changes at the
    // end of the active lifecycle.
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // Save UI state changes to the savedInstanceState.
        // This bundle will be passed to onCreate and
        // onRestoreInstanceState if the process is
        // killed and restarted by the run time.
        super.onSaveInstanceState(savedInstanceState);
    }

    // Called at the end of the active lifetime.
    @Override
    public void onPause(){
        // Suspend UI updates, threads, or CPU intensive processes
        // that don�t need to be updated when the Activity isn�t
        // the active foreground Activity.
        super.onPause();
    }

    // Called at the end of the visible lifetime.
    @Override
    public void onStop(){
        // Suspend remaining UI updates, threads, or processing
        // that aren�t required when the Activity isn�t visible.
        // Persist all edits or state changes
        // as after this call the process is likely to be killed.
        super.onStop();
    }

    // Sometimes called at the end of the full lifetime.
    @Override
    public void onDestroy(){
        // Clean up any resources including ending threads,
        // closing database connections etc.
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onDownloadFinish(List<Item> result) {
        Log.d(MainActivity.DEBUG, "Listen in onFinised");
        if (result != null) {

            for (Item i : result){
                String startPattern = "(<p>)";
                String endPattern = "(</p>)";
                String desc[] = i.getDescription().split(endPattern);
                Log.d(MainActivity.DEBUG, i.getTitle());
                Log.d(MainActivity.DEBUG, desc[0].replaceFirst(startPattern, ""));
            }
        }
        else {
            Log.d(MainActivity.DEBUG, "Download failed");
        }
    }
}
